package com.dingdang.util;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;

public class ClientChat extends JFrame {
    private static final String LOCATION = "127.0.0.1";
    private static final int LOCATION_PORE=8888;
    private Socket socket = null;
    private JTextArea ta =  new JTextArea(10,20);
    private JScrollPane sp = new JScrollPane(ta);
    private JTextField tf = new JTextField(20);
    private DataOutputStream dos = null;
    private  boolean isConn = false;
//初始化方法
    public void init(){
        this.setTitle("客户端窗口");
        this.add(sp, BorderLayout.CENTER);
        this.add(tf,BorderLayout.SOUTH);
//        设置大小
        this.setBounds(300,300,300,400);
        tf.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
//                获取消息
                String strSend = tf.getText();

                if (strSend.trim().length()==0){
                    return;
                }
//                调用发送消息方法将消息发送到服务器上
                sendMessage(strSend);

                tf.setText("");
//                ta.append(strSend+"\n");
            }
        });

//        增加监听
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//        光标聚焦
        tf.requestFocus();

        try {
            socket = new Socket(LOCATION,LOCATION_PORE);//连接服务器
            isConn=true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.setVisible(true);
//        开启多线程
        new Thread(new Receive()).start();

    }
//发送消息到服务器上的方法
    public void sendMessage(String str){
        try {
            dos = new DataOutputStream(socket.getOutputStream());
//            将消息写到服务中
            dos.writeUTF(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    class Receive implements Runnable{
        @Override
        public void run() {

            try {
                while (isConn) {
                    DataInputStream dis = new DataInputStream(socket.getInputStream());
                    String str = dis.readUTF();
                    ta.append(str);
                }

            } catch (SocketException e) {
                System.out.println("服务器以外停止!");
                ta.append("服务器意外停止!\n");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ClientChat chat = new ClientChat();
        chat.init();

    }
}
